package com.example.websocketdemo.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.websocketdemo.entity.event.InvasionEvents;
import com.example.websocketdemo.entity.event.InvasionFielddetection;
import com.example.websocketdemo.entity.event.InvasionRegionCoordinates;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.Field;

@RestController
@RequestMapping("/event")
public class RegionalInvasionController {
//    @Autowired
//    private InvasionEventsMapper invasionEventsMapper;
//
//    @Autowired
//    private InvasionFielddetectionMapper invasionFielddetectionMapper;
//
//    @Autowired
//    private InvasionRegionCoordinatesMapper invasionRegionCoordinatesMapper;
//
//    private static final Logger logger = LogManager.getLogger(RegionalInvasionController.class);
//    private static final int WELINK_MODEL_ID = 200455;

    @PostMapping("/regionalInvasion")
    private void firstLayer(@RequestBody JSONObject jsonObject1) throws IllegalAccessException {
        String ab = jsonObject1.toString();
        String ab2 = "{\"method\":\"OnEventNotify\",\"params\":{\"ability\":\"event_rule\",\"events\":[{\"data\":{\"dataType\":\"behavioralAnalysis\",\"recvTime\":\"2022-06-10T15:39:01+08:00\",\"sendTime\":\"2022-06-10T15:39:01+08:00\",\"dateTime\":\"2022-06-10T15:39:01+08:00\",\"ipAddress\":\"10.19.134.11\",\"portNo\":80,\"channelID\":1,\"eventType\":\"fielddetection\",\"eventDescription\":\"fielddetection\",\"fielddetection\":[{\"targetAttrs\":{\"imageServerCode\":\"3212234\",\"deviceIndexCode\":\"1568556\",\"cameraIndexCode\":\"1235415\",\"channelName\":\"tongdao1\",\"cameraAddress\":\"\",\"longitude\":116.39737,\"latitude\":116.39737},\"imageUrl\":\"http://10.3.1.12:8080/xxx\",\"duration\":120,\"sensitivityLevel\":20,\"rate\":30,\"detectionTarget\":1,\"regionCoordinatesList\":[{\"positionX\":0.901,\"positionY\":0.536},{\"positionX\":0.901,\"positionY\":0.536}]}]},\"eventId\":\"BE26E09F-0C6C-4EF9-BE2B-27007B261731\",\"eventType\":131588,\"happenTime\":\"2022-06-10T15:17:24.000+08:00\",\"srcIndex\":\"da107dd1989e44978a5efebe73d6e979\",\"srcName\":\"屋顶-4\",\"srcType\":\"camera\",\"status\":0,\"timeout\":0}],\"sendTime\":\"2019-01-02T15:19:59.857+08:00\"}}\n";
        JSONObject jsonObject = JSONObject.parseObject(ab2);
        System.out.println("================调用区域入侵方法=====================");
        System.out.println(ab);
        JSONArray events = (JSONArray) ((JSONObject) jsonObject.get("params")).get("events");
        for (int i = 0; i < events.size(); i++) {
            InvasionEvents invasionEvents = new InvasionEvents();
            JSONObject json = (JSONObject) events.get(i);
            invasionEvents.setEventId((String) json.get("eventId"));
            invasionEvents.setEventType((int) json.get("eventType"));
            invasionEvents.setHappenTime((String) json.get("happenTime"));
            invasionEvents.setSrcIndex((String) json.get("srcIndex"));
            invasionEvents.setSrcName((String) json.get("srcName"));
            invasionEvents.setSrcType((String) json.get("srcType"));
            invasionEvents.setStatus((int) json.get("status"));
            invasionEvents.setTimeout((int) json.get("timeout"));
            invasionEvents.setDataDataType((String) ((JSONObject) json.get("data")).get("dataType"));
            invasionEvents.setDataRecvTime((String) ((JSONObject) json.get("data")).get("recvTime"));
            invasionEvents.setDataSendTime((String) ((JSONObject) json.get("data")).get("sendTime"));
            invasionEvents.setDataDateTime((String) ((JSONObject) json.get("data")).get("dateTime"));
            invasionEvents.setDataIpAddress((String) ((JSONObject) json.get("data")).get("ipAddress"));
            invasionEvents.setDataPortNo((int) ((JSONObject) json.get("data")).get("portNo"));
            invasionEvents.setDataChannelID((int) ((JSONObject) json.get("data")).get("channelID"));
            invasionEvents.setDataEventType((String) ((JSONObject) json.get("data")).get("eventType"));
            invasionEvents.setDataEventDescription((String) ((JSONObject) json.get("data")).get("eventDescription"));
            String timeStamp = String.valueOf(System.currentTimeMillis());
            invasionEvents.setDataFielddetection(timeStamp);
//            invasionEventsMapper.insert(invasionEvents);
            JSONArray fielddetections = (JSONArray) ((JSONObject) json.get("data")).get("fielddetection");
            secondFloor(fielddetections, timeStamp, invasionEvents);
        }
    }

    public void secondFloor(JSONArray fielddetections, String timeStamp, InvasionEvents invasionEvents) throws IllegalAccessException {
        for (int i = 0; i < fielddetections.size(); i++) {
            InvasionFielddetection invasionFielddetection = new InvasionFielddetection();
            JSONObject json = (JSONObject) fielddetections.get(i);
            invasionFielddetection.setImageServerCode((String) ((JSONObject) json.get("targetAttrs")).get("imageServerCode"));
            invasionFielddetection.setDeviceIndexCode((String) ((JSONObject) json.get("targetAttrs")).get("deviceIndexCode"));
            invasionFielddetection.setCameraIndexCode((String) ((JSONObject) json.get("targetAttrs")).get("cameraIndexCode"));
            invasionFielddetection.setChannelName((String) ((JSONObject) json.get("targetAttrs")).get("channelName"));
            invasionFielddetection.setCameraAddress((String) ((JSONObject) json.get("targetAttrs")).get("cameraAddress"));
            System.out.println(Float.parseFloat(((JSONObject) json.get("targetAttrs")).get("longitude").toString()));
            invasionFielddetection.setLongitude(Float.parseFloat(((JSONObject) json.get("targetAttrs")).get("longitude").toString()));
            invasionFielddetection.setLatitude(Float.parseFloat(((JSONObject) json.get("targetAttrs")).get("latitude").toString()));
            invasionFielddetection.setImageUrl((String) json.get("imageUrl"));
            invasionFielddetection.setDuration((int) json.get("duration"));
            invasionFielddetection.setSensitivityLevel((int) json.get("sensitivityLevel"));
            invasionFielddetection.setRate((int) json.get("rate"));
            invasionFielddetection.setDetectionTarget((int) json.get("detectionTarget"));
            invasionFielddetection.setDataFielddetection(timeStamp);
            String timeStampRegionCoordinates = String.valueOf(System.currentTimeMillis());
            invasionFielddetection.setRegionCoordinates(timeStampRegionCoordinates);
//            invasionFielddetectionMapper.insert(invasionFielddetection);
            JSONArray regionCoordinates = (JSONArray) json.get("regionCoordinatesList");
            thirdLayer(regionCoordinates, timeStampRegionCoordinates, invasionEvents, invasionFielddetection);
        }


    }

    public void thirdLayer(JSONArray regionCoordinates, String timeStamp, InvasionEvents invasionEvents, InvasionFielddetection invasionFielddetection) throws IllegalAccessException {
        for (int i = 0; i < regionCoordinates.size(); i++) {
            System.out.println("123");
            InvasionRegionCoordinates invasionRegionCoordinates = new InvasionRegionCoordinates();
            JSONObject json = (JSONObject) regionCoordinates.get(i);
            invasionRegionCoordinates.setPositionX(Float.parseFloat(json.get("positionX").toString()));
            invasionRegionCoordinates.setPositionY(Float.parseFloat(json.get("positionY").toString()));
            invasionRegionCoordinates.setRegionCoordinates(timeStamp);
//            invasionRegionCoordinatesMapper.insert(invasionRegionCoordinates);
            send(invasionEvents, invasionFielddetection, invasionRegionCoordinates);
        }
    }

    public void send(InvasionEvents invasionEvents, InvasionFielddetection invasionFielddetection, InvasionRegionCoordinates invasionRegionCoordinates) throws IllegalAccessException {
//        JSONObject standardData = new JSONObject();
//        standardData.put("reportTs", System.currentTimeMillis());
//        JSONObject profile = new JSONObject();
//        profile.put("modelId", WELINK_MODEL_ID);
//        profile.put("appType", "regionalInvasion");
//        profile.put("pioCode", "w0721000");
//        profile.put("din", "200900000000019107");
//        standardData.put("profile", profile);
//        JSONObject events = new JSONObject();
        JSONObject event = new JSONObject();
        for (Field field : invasionEvents.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            event.put(field.getName(),field.get(invasionEvents));
        }
        for (Field field : invasionFielddetection.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            event.put(field.getName(),field.get(invasionFielddetection));
        }
        for (Field field : invasionRegionCoordinates.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            event.put(field.getName(),field.get(invasionRegionCoordinates));
        }
        System.out.println(event.toString());
//        events.put("appointment", event);
//        standardData.put("events", events);
//        standardData.put("properties", new JSONObject());
//        try {
//            String devRunEvent = JSONObject.toJSONString(standardData, SerializerFeature.WriteMapNullValue);
//            System.out.println("devRunEvent：" + devRunEvent);
//            sendMessage(standardData, "200900000000019107");
//            logger.info("===========区域入侵==========");
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("设备运行时事件数据传输出现异常");
//        }
    }
//
//    private void sendMessage(JSONObject standardData, String subDin) {
//        System.out.println("发送");
//        try {
//            new WelinkMqtt(RegularInstance.registerData1, RegularInstance.loginData, standardData, RegularInstance.clientByZJ, subDin);
//        } catch (Exception e) {
//            logger.error(e.getMessage());
//            e.printStackTrace();
//        }
//    }
}
